import { sys } from "cc";
import { CustomEventListener } from "./CustomEventListener";
import { GameCrypto } from "../utils/GameCrypto";
import { Constants } from "../configs/Constants";
import { L2EProtocol } from "../proto/ELProtocol";
import { Utils } from "../utils/utils";
import { UserInfo } from "./UserData";


export const RELOGIN_MAX_COUNT = 1;

export class GameData {
    private user: UserInfo = null;

    private hasToken: boolean = false;
    private bTokenOvertime: boolean = false;
    private reloginCount: number = RELOGIN_MAX_COUNT;

    // 登录错误 0： 无误， 1： 超过重登次数， 2： 无用户密码
    private loginError: number = 0;
    // 准备好进入大厅的数据
    private ready2Hall: boolean = false;
    // todo 直接进游戏
    private ready2Game: boolean = false;

    constructor() {
        this.user = <UserInfo>{};
    }

    public checkToken() {
        let tokenStr = localStorage.getItem("local_account_token");
        if (tokenStr === "undefined") {
            tokenStr = undefined;
        }
        let token = globalThis.account_token = tokenStr;
        this.hasToken = (token!==undefined);
        return this.hasToken;
    }

    public isHasToken() {
        return this.hasToken;
    }

    public isReady2Hall() {
        return this.ready2Hall;
    }

    public isReady2Game() {
        return this.ready2Game;
    }


    public resetReloginCount() {
        this.reloginCount = RELOGIN_MAX_COUNT;
        this.loginError = 0;
    }

    public checkReloginCount() {
        return this.reloginCount > 0;
    }

    public doInvalidToken() {
        // 无效token
        if (this.checkReloginCount() === true) {
            // 重登一次
            this.reloginCount--;
            this.doLogin();
            return;
        }

        // 没有重登次数
        this.loginError = 1;
        CustomEventListener.dispatchEvent(Constants.EventName.LOGIN_ERROR, this.loginError);
    }

    public doLogin(accountStr?: string, passwordStr?: string) {
        var lastLoginType = localStorage.getItem("local_last_login_type");
        if (lastLoginType === "undefined") {
            lastLoginType = "";
        }
        
        if (!accountStr) {
            accountStr = localStorage.getItem("local_last_login_account");
            if (accountStr === "undefined") {
                accountStr = "";
            }
        }
        if (!passwordStr) {
            passwordStr = localStorage.getItem("local_last_login_password") || "";
            if (passwordStr === "undefined") {
                passwordStr = "";
            }
        }

        if (lastLoginType == "wx" || lastLoginType == "qq") {
            // 跳转微信QQ第三方登录
            return;
        }

        // 数据异常，无法重登！！！
        if (accountStr == "" || passwordStr == "") {
            this.loginError = 2;
            CustomEventListener.dispatchEvent(Constants.EventName.LOGIN_ERROR, this.loginError);
            return;
        }

        var requestData = {};
        requestData["channelCode"] = globalThis.channelId;
        requestData["account"] = accountStr;
        requestData["password"] = escape(passwordStr);
        requestData["token"] = globalThis.account_token || "";
        if (globalThis.account_token === "undefined") {
            requestData["token"] = "";
        }
        requestData["openId"] = "";
        // 登录方式（默认0账号密码登录，其他SDK登录）
        requestData["loginType"] = 0;
        requestData["ts"] = sys.now();

        var currType = "login";
        var originStr = "key=" + Constants.ENCRYPT_KEY + "&ts=" + requestData["ts"] + "&type=" + currType;
        console.log("makeLoginOnce >>>> originStr:" + originStr);
        var signStr = GameCrypto.md5(originStr);
        console.log("makeLoginOnce >>>> sign:" + signStr);
        requestData["sign"] = String(signStr);
        requestData["imei"] = "";

        var dataStr = "channelCode=" + requestData["channelCode"] +
            "&account=" + requestData["account"] +
            "&password=" + requestData["password"] +
            "&token=" + requestData["token"] +
            "&openId=" + requestData["openId"] +
            "&sign=" + requestData["sign"] +
            "&loginType=" + requestData["loginType"] +
            "&ts=" + requestData["ts"];
        //     "&imei=" + requestData.imei;
        console.log("makeLoginOnce >>>> data:" + dataStr);

        CustomEventListener.dispatchEvent(Constants.EventName.HTTP_REQUEST, "login_account", Constants.account_login_url, "POST", dataStr);
    }

    public loginComplete(data: any) {
        globalThis.account_id = data.accountId;
        globalThis.account_token = data.token;
        globalThis.last_login_time = sys.now();

        // 【实名认证】状态(state 0已/1中/2失败/-1未)
        globalThis.idcard_check_state = data.realNameStatus;

        localStorage.setItem("local_account_id", globalThis.account_id);
        localStorage.setItem("local_account_token", globalThis.account_token);
        localStorage.setItem("idcard_check_state", String(globalThis.idcard_check_state));
        localStorage.setItem("local_login_time", globalThis.last_login_time);

        this.wsAddrRequest();
    }

    public wsAddrRequest() {
        // var self = this;

        // // 是否需要【实名认证】弹窗
        // var is_idcard_need = api_is_idcard_need();
        // if (is_idcard_need == true) {
        //     // 强制【实名认证】弹窗
        //     self.idcard_check(true);
        //     return;
        // }

        var dataStr = "";
        var token = globalThis.account_token;
        console.log("loading ---- on_ws_addr_request ---- token:" + token);

        CustomEventListener.dispatchEvent(Constants.EventName.HTTP_REQUEST, "ws_addr_request", Constants.account_selectgateway_url, "POST", dataStr);
    }

    public wsAddrResponse(data: any, code?: number) {

        // 获取ws地址成功
        console.log("loading ws addr response:" + JSON.stringify(data));
        data.ip = "192.168.1.15";
        data.port = "9942";
        if (data.path) {
            Constants.center_server_url = data.path;
        } else {
            Constants.center_server_url = Constants.game_connect_type + "://" + Utils.api_fix_ws_addr_url(data.ip, data.port);
        }
        console.log("loading ---- core_notify_http_response_successful ---- ws_addr_request :" + Constants.center_server_url);
        // 获取ws地址成功-->连接ws-->认证ws-->获取userinfo-->【资源加载完成】-->跳转大厅
        this.connectWs();
    }

    public wsAddrResponseFail(data: any, code?: number) {
        // 获取ws地址失败
        Constants.center_server_url = "";
        console.log("获取ws地址失败");

        if (code == undefined || code < 0) {
            var continue_fun = function () {
                this.wsAddrRequest();
            }

            CustomEventListener.dispatchEvent(L2EProtocol.l2e_open_msg_box, {
                "type": Constants.BOX_BTN_TYPE.continue,
                "text": "没有网关信息，无法连接游戏！\n点击【确定】重新连接？",
                "continue_fun": continue_fun,
                "fairy": 1
            });
            return;
        }

        if (code == 601) {

            // token过期-->读取本地token对应的账号密码-->重登一次
            this.resetReloginCount();
            this.doLogin();
        } else {
            CustomEventListener.dispatchEvent(L2EProtocol.l2e_open_msg_box, {
                "type": Constants.BOX_BTN_TYPE.know,
                "text": data || "获取ws地址失败",
                "fairy": 1
            });
        }
    }

    private connectWs() {
        var self = this;

        var connect_successful = function () {
            console.log("连接游戏服务器 认证ws");
            // 认证ws-->获取userinfo-->【资源加载完成】-->跳转大厅

            // token为空，等待登录中，不再自动重连
            if (!globalThis.account_token || globalThis.account_token === "undefined" || globalThis.account_token.length <= 0) {
                console.log("token为空，等待登录中，不再自动重连");
                // this.webSock.onCancel();
                CustomEventListener.dispatchEvent(Constants.EventName.WS_CANCEL_CONFIRM);
                return;
            }    

            // 认证ws
            var data : IRequestProto = {
                cmd: COMMON_PB_COMMAND.MSG_CONFIRM_REQUEST,
            }
            data.confirmRequest = {
                token: globalThis.account_token
            }
            CustomEventListener.dispatchEvent(Constants.EventName.WS_REQ_PB, data);
        }

        var connect_failed = function () {
            console.log("连接游戏服务器失败!");
            CustomEventListener.dispatchEvent(L2EProtocol.l2e_open_msg_box, {
                "type": Constants.BOX_BTN_TYPE.know,
                "text": "连接游戏服务器失败!\n请确保网络正常后再尝试",
                "fairy": 1
            });
        }

        console.log("连接游戏服务器 ---- center_server_url :" +  Constants.center_server_url);
        CustomEventListener.dispatchEvent(Constants.EventName.CONN_WS, 
            Constants.center_server_url, connect_successful, connect_failed);
    }

    public doRegiste(accountStr: string, passwordStr: string, validCode: string) {
        var requestData = {};
        requestData["channelCode"] = globalThis.channelId;
        requestData["account"] = accountStr;
        requestData["password"] = escape(passwordStr);
        requestData["validCode"] = escape(validCode);
        requestData["ts"] = sys.now();

        var currType = "register";
        var originStr = "key=" + Constants.ENCRYPT_KEY + "&ts=" + requestData["ts"] + "&type=" + currType;
        console.log("makeRegister >>>> originStr:" + originStr);
        var signStr = GameCrypto.md5(originStr);
        console.log("makeRegister >>>> sign:" + signStr);
        requestData["sign"] = String(signStr);
        requestData["imei"] = "";

        var dataStr = "channelCode=" + requestData["channelCode"] +
            "&account=" + requestData["account"] +
            "&password=" + requestData["password"] +
            "&token=" + requestData["token"] +
            "&openId=" + requestData["openId"] +
            "&sign=" + requestData["sign"] +
            "&loginType=" + requestData["loginType"] +
            "&ts=" + requestData["ts"];
        //     "&imei=" + requestData.imei;
        console.log("makeLoginOnce >>>> data:" + dataStr);

        CustomEventListener.dispatchEvent(Constants.EventName.HTTP_REQUEST, "registe_account", Constants.account_register_url, "POST", dataStr);
    }

    public doRequestUserinfo() {
        var data : IRequestProto = {
            cmd: COMMON_PB_COMMAND.MSG_GET_USER_INFO_REQUEST,
        }
        CustomEventListener.dispatchEvent(Constants.EventName.WS_REQ_PB, data);
    }

    public parseUserInfo(data: any) {
        // JSON.stringify(data);
    }
}

